from flow_alchemy.core.globals import session,task
from flow_alchemy.core.controller import Controller
from flow_alchemy.db.models import PR, User

ctrl = Controller(id=1000, name='example_pr', category='财务部', model=PR)

start = ctrl.start
erp = ctrl.make.ERPNode(nid=1200, name='PR预处理')
user_app1 = ctrl.make.UserNode(nid=1301, name='财务主管')
user_app2 = ctrl.make.UserNode(nid=1302, name='财务经理')
role_app = ctrl.make.RoleNode(nid=1400, name='budget owner')
and_node = ctrl.make.AndNode(nid=1500, name='and')
cfo = ctrl.make.UserNode(nid=1601, name='CFO')
ceo = ctrl.make.UserNode(nid=1602, name='CEO')
or_node = ctrl.make.OrNode(nid=1700, name='or')
end = ctrl.end

start.case.passed(erp)
erp.case.passed(user_app1, role_app)
user_app1.case.passed(user_app2)
user_app2.case.passed(and_node)
role_app.case.passed(and_node)


@and_node.edge(cfo, '总金额>=1000')
def total_gt_1000(pr):
    return pr.total >= 1000


@and_node.edge(ceo, '总金额<1000')
def total_lt_1000(pr):
    return pr.total < 1000


cfo.case.passed(or_node)
ceo.case.passed(or_node)
or_node.case.passed(end)


@erp.erp_process
def erp_process1(pr):
    """set total"""
    USD = 6 if pr.currency == 'USD' else 1
    EUR = 8 if pr.currency == 'EUR' else 1
    pr.total = pr.count * pr.price * USD * EUR


@erp.erp_process
def erp_process2(pr, submitter, task):
    """set PR NO."""
    pr.pr_no = 'PR%s@%s' % (task.tid, submitter.uid)


@ctrl.loading(name='pr', lazy=True)
def get_pr_data():
    return session.query(PR).filter_by(tid=task.tid).first()


@ctrl.loading(name='submitter', readonly=True)
def get_user():
    return session.query(User).filter_by(uid=task.uid).first()